package com.vr.cloudpicture.api.imagesearch.sub;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.vr.cloudpicture.exception.BusinessException;
import com.vr.cloudpicture.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取图像页面 API
 *
 * @author hzh
 * @date 2025/05/20
 */
@Slf4j
public class GetImagePageApi {
    /**
     * 获取图像页面 URL
     *
     * @param imageUrl 图片 URL
     * @return {@code String }
     */
    public static String getImagePageUrl(String imageUrl) {
        // 1.准备请求参数
        HashMap<String, Object> formData = new HashMap<>();
        formData.put("image", imageUrl);
        formData.put("tn", "pc");
        formData.put("from", "pc");
        formData.put("image_source", "PC_UPLOAD_URL");
        // 获取当前时间戳
        long uptime = System.currentTimeMillis();
        // 请求地址
        String url = "https://graph.baidu.com/upload?uptime=" + uptime;
        try {
            // 2.发送Post请求到百度接口
            HttpResponse response = HttpRequest.post(url)
                    .header("Acs-Token", RandomUtil.randomString(1))
                    .form(formData)
                    .timeout(5000)
                    .execute();
            // 判断响应状态
            if (!response.isOk()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"接口调用失败");
            }
            // 解析响应
            String responseBody = response.body();
            Map<String,?> result = JSONUtil.toBean(responseBody, Map.class);

            // 3.处理返回结果
            if (result==null || !Integer.valueOf(0).equals(result.get("status"))) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"接口调用失败");
            }
            Map<String, ?> data = (Map<String, ?>) result.get("data");
            String rawUrl = (String) data.get("url");
            // 对url进行解码
            String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            if (searchResultUrl==null) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"未返回有效的结果");
            }
            return searchResultUrl;
        } catch (Exception e) {
            log.error("搜索失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"搜索失败");
        }
    }

    public static void main(String[] args) {
        System.out.println(getImagePageUrl("https://www.beijing.gov.cn/renwen/bjgk/mygk/myfg/202208/W020220812574023612181.jpg"));
    }
}
